package com.chery.media.music

import android.app.Service
import android.content.Intent
import android.media.AudioDeviceInfo
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import com.blankj.utilcode.util.Utils
import com.chery.media.contacts.EventContacts
import com.chery.media.library.extend.toast
import com.chery.media.network.model.MusicBean
import com.chery.media.network.model.MusicPlayBean
import com.chery.media.ui.music.musicViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import java.util.Timer
import java.util.TimerTask

class MusicService: Service(), MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener {

    val musicList = arrayListOf<MusicBean>()

    var mMediaPlayer: MediaPlayer? = null

    var timer: Timer? = null

    var currentPosition = 0

    var music: MusicBean? = null

    override fun onBind(intent: Intent?): IBinder? = MusicBinder()

    override fun onCreate() {
        super.onCreate()
        mMediaPlayer = MediaPlayer()
        mMediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mMediaPlayer?.setOnCompletionListener(this)
        mMediaPlayer?.setOnErrorListener(this)
        mMediaPlayer?.setOnPreparedListener(this)
    }

    /**
     * 设置音乐列表
     */
    fun setMusicList(list: ArrayList<MusicBean>, isAdd: Boolean = false){
        if (isAdd.not()) musicList.clear()
        musicList.addAll(list)
    }

    //获取播放进度
    fun getMusicCurrentTime(): Int = mMediaPlayer?.currentPosition?:0

    fun startPlay(){
        if (currentPosition >= musicList.size) return
        music = musicList[currentPosition]
        if (music?.title.isNullOrEmpty()) {
            val name = music?.playPath?.substring(music?.playPath!!.lastIndexOf("/") + 1, music?.playPath!!.lastIndexOf(".")) ?: ""
            LiveEventBus.get<String>(EventContacts.MUSIC_NAME).post(name)
        } else {
            LiveEventBus.get<String>(EventContacts.MUSIC_NAME).post(music?.title)
        }
        LiveEventBus.get<String>(EventContacts.MUSIC_SINGER).post(music?.author)
        try {
//            mMediaPlayer?.setDataSource(music?.playPath)
            mMediaPlayer?.setDataSource("http://m801.music.126.net/20240131231515/f7c96174a852b0cf057e072455fedd7d/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/30093235102/cea1/ab76/8bd7/fc7cfd352b612c08b2cb44ca600adafd.mp3")
            mMediaPlayer?.prepare()
//            mMediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
            sendCurrentMusic()
            "播放失败".toast()
        }
    }

    private fun startTimer(){
        if (timer == null ) timer = Timer()
        timer?.schedule(object : TimerTask(){
            override fun run() {
                sendCurrentMusic()
            }

        }, 0, 1000)
    }

    private fun stopTimer(){
        timer?.cancel()
        timer = null
    }

    private fun sendCurrentMusic(){
        val name = if (music?.title.isNullOrEmpty()) {
            music?.playPath?.substring(music?.playPath!!.lastIndexOf("/") + 1, music?.playPath!!.lastIndexOf(".")) ?: ""
        } else {
            music?.title
        }
        val currentMusic = MusicPlayBean(
            currentPosition,
            music?.author,
            music?.cover,
            music?.lyricPath,
            name,
            "${getMusicCurrentTime()}",
            "${mMediaPlayer?.duration?:0}",
            mMediaPlayer?.isPlaying
        )
        musicViewModel.currentPlayMusic.postValue(currentMusic)
    }

    fun playNext(){
        currentPosition = if (currentPosition == musicList.size - 1) (currentPosition + 1) % musicList.size else currentPosition + 1
        mMediaPlayer?.reset()
        startPlay()
    }

    fun playPre(){
        currentPosition = if (currentPosition == 0) 0 else currentPosition - 1
        mMediaPlayer?.reset()
        startPlay()
    }

    fun playPause(){
        mMediaPlayer?.pause()
    }

    fun playReset(){
        mMediaPlayer?.reset()
        stopTimer()
    }

    fun play(position: Int = -1){
        if (position != -1) {
            if (position >= musicList.size) return
            currentPosition = position
            mMediaPlayer?.reset()
            startPlay()
        } else {
            mMediaPlayer?.start()
        }
    }

    inner class MusicBinder: Binder(){

        fun getMusicService(): MusicService = this@MusicService

        fun getMediaPlayer(): MediaPlayer? = mMediaPlayer

        fun seekTo(position: Int) {
            mMediaPlayer?.seekTo(position)
        }

    }

    override fun onCompletion(mp: MediaPlayer?) {
        stopTimer()
        playNext()
    }

    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        "播放失败".toast()
        stopTimer()
        return false
    }

    override fun onPrepared(mp: MediaPlayer?) {
        mp?.start()
        startTimer()
    }

}